<?php
// +----------------------------------------------------------------------
// | author: thinkphp
// +----------------------------------------------------------------------

namespace app\adminapi\controller;


use app\common\cache\ExportCache;
use app\common\service\JsonService;

class DownloadController extends BaseAdminController
{

    public array $notNeedLogin = ['export', 'download'];

    /**
     * @notes 导出文件
     * @return \think\response\File|\think\response\Json
     */
    public function export()
    {
        //获取文件缓存的key
        $fileKey = request()->get('file');

        //通过文件缓存的key获取文件储存的路径
        $exportCache = new ExportCache();
        $fileInfo = $exportCache->getFile($fileKey);

        if (empty($fileInfo)) {
            return JsonService::fail('下载文件不存在');
        }

        //下载前删除缓存
        $exportCache->delete($fileKey);

        return download($fileInfo['src'] . $fileInfo['name'], $fileInfo['name']);
    }

    public function download()
    {
        try {
            // 获取文件名
            $fileName = request()->get('file', '');

            // 文件名校验（防止路径穿越攻击）
            if (empty($fileName) || !preg_match('/^[a-zA-Z0-9_\-\.\s]+$/u', $fileName)) {
                return JsonService::fail('非法文件名');
            }

            // 构建文件路径
            $filePath = runtime_path() . 'template' . DIRECTORY_SEPARATOR . $fileName;
            // 检查文件是否存在
            if (!file_exists($filePath)) {
                return JsonService::fail('文件不存在');
            }

            return $_SERVER['HTTP_HOST']. '/uploads/template/'.$fileName;

//            var_dump(request());

//            return download($_SERVER['HTTP_HOST']. '/uploads/template/'.$fileName, $fileName);

        } catch (\Exception $e) {
            return JsonService::fail('下载失败: ' . $e->getMessage());
        }
    }
}